package com.su.sweet.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.su.sweet.model.SUser;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;
import org.noear.solon.sessionstate.jwt.JwtUtils;

//@Component
public class TokenFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        String token = ctx.header("authorization");
        if (Utils.isNotEmpty(token)) {
            try {
                SUser user = (SUser) JwtUtils.parseJwt(token).get("user");
                ctx.headerMap().put("userId", user.getId().toString());
            } catch (Exception ex) {
                ex.printStackTrace();
                ctx.outputAsJson(JSON.toJSONString(Result.failure(10020)));
            }
        }
        chain.doFilter(ctx);
    }
}
